package com.web;

import com.dao.PhoneDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/phone/add")
public class PhoneAddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/phone/phoneAdd.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String price = req.getParameter("price");
        String model = req.getParameter("model");
        String color = req.getParameter("color");
        String origin = req.getParameter("origin");

        if (name == null || price == null || model == null || color == null || origin == null) {
            req.setAttribute("message", "参数不对");
            req.getRequestDispatcher("/phone/message.jsp").forward(req, resp);
            return;
        }
        try {
            new PhoneDao().insert(name, Float.parseFloat(price), model, color, origin);

            req.setAttribute("message", "添加成功");
            req.getRequestDispatcher("/phone/message.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("message", "添加失败！" + e.getLocalizedMessage());
            req.getRequestDispatcher("/phone/message.jsp").forward(req, resp);
        }
    }
}
